import { httpClient } from '@/config'
import type { AxiosProgressEvent } from 'axios'


/**
 * 文件上传
 */
export function fileUpload(param: FileUploadParam) {
    const { file, onUploadProgress, originalName, groupId, abortController } = param

    return httpClient.upload<SysFileUploadResponse>({
        url: '/file/upload',
        method: 'POST',
        headers: {
            'Content-Type': 'application/octet-stream',
        },
        signal: abortController?.signal,
        onUploadProgress,
        data: file,
        params: {
            originalName,
            groupId,
        },
        timeout: 5 * 60 * 1000,
    })
}

/**
 * 读取文件
 * @param uri 资源引用字符串
 * @param redirect 使用重定向还是正常响应, 默认重定向
 */
export function readFile(uri: string, redirect?: boolean) {
    return httpClient.send<Blob | TemporaryUrl>({
        url: '/file',
        method: 'GET',
        params: { uri, redirect },
        responseType: redirect === false ? 'json' : 'blob',
    })
}

/**
 * 读取文件
 * @param encodingUri 编码后的资源引用字符串
 * @param redirect 使用重定向还是正常响应, 默认重定向
 */
export function getFile(encodingUri: string, redirect?: boolean) {
    return httpClient.send<Blob | TemporaryUrl>({
        url: '/file/' + encodingUri,
        method: 'GET',
        params: { redirect },
        responseType: redirect === false ? 'json' : 'blob',
    })
}


export interface FileUploadParam {

    file: Blob

    originalName: string,

    groupId?: string

    onUploadProgress?: (event: AxiosProgressEvent) => void

    abortController?: AbortController

}

export interface SysFileUploadResponse {

    id: string

    uri: string

    url: TemporaryUrl
}


export interface TemporaryUrl {

    method: string

    url: string

    headers: Record<string, string>

    expiration: string | null
}
